#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cassert>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <strings.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFFER_NUM 1024

enum {
    SOCKET_ERR = 1,
    BIND_ERR,
    USAGE_ERR,
    SENDTO_ERR,
    RECVFROM_ERR
};

class UdpClient
{
public:
    UdpClient(const std::string serverip, const uint16_t serverport):_serverip(serverip), _serverport(serverport), _quit(false)
    {}

    void init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd == -1)
        {
            std::cerr << errno << ": "<< strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        //客户端不需要进行绑定
    }

    static void* read_message(void* args)
    {
        pthread_detach(pthread_self());
        std::string msg;
        int _socketfd = *(static_cast<int*>(args));
        char buffer[BUFFER_NUM];
        struct sockaddr_in temp;
        socklen_t templen = sizeof(temp);
        while(true)
        {
            int n = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &templen);
            //该函数会进行阻塞式等待消息
            if(n == -1)
            {
                std::cerr << errno << ": "<< strerror(errno) << std::endl;
                exit(RECVFROM_ERR);
            }
            buffer[n] = 0;
            msg = buffer;
            // std::cout << "服务器返回结果# " << msg << std::endl;
            std::cout << msg << std::endl;
        }
    }

    void run()
    {
        pthread_create(&reader, nullptr, read_message, &_socketfd);
        struct sockaddr_in server;
        // bzero(&server, sizeof(server));
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        server.sin_port = htons(_serverport);
        socklen_t serverlen = sizeof(server);
        std::string msg;
        char command_line[BUFFER_NUM];
        while(!_quit)
        {
            std::cerr << "Please Enter# ";
            fgets(command_line, sizeof(command_line)-1, stdin);//cin会自动将空格切割
            command_line[strlen(command_line)-1] = 0;
            msg = command_line;
            int n = sendto(_socketfd, msg.c_str(), msg.size(), 0, (struct sockaddr*)&server, sizeof(server));
            if(n == -1)
            {
                std::cerr << errno << ": "<< strerror(errno) << std::endl;
                exit(SENDTO_ERR);
            }
        }
        close(_socketfd);
    }
    
    ~UdpClient()
    {}
private:
    std::string _serverip;//点分十进制
    uint16_t _serverport;//服务端的端口
    int _socketfd;//打开的文件描述符
    pthread_t reader;//用子线程来读取数据，父线程用来写数据
    bool _quit;
};